import { createRouter, createWebHistory, createMemoryHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

// 检测是否在微前端环境中运行
const isMicroApp = (): boolean => {
  return (
    !!(window as unknown as { __MICRO_APP_ENVIRONMENT__?: boolean }).__MICRO_APP_ENVIRONMENT__ ||
    window.parent !== window
  )
}

const router = createRouter({
  // 在微前端环境中使用 Memory History，避免与主应用路由冲突
  history: isMicroApp() ? createMemoryHistory() : createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue'),
    },
  ],
})

// 在微前端环境中监听来自主应用的路由变化
if (isMicroApp()) {
  console.log('子应用 A 在微前端环境中运行')
  console.log('当前window对象信息:', {
    hasMicroApp: !!(window as unknown as { microApp?: unknown }).microApp,
    microAppMethods: (window as unknown as { microApp?: Record<string, unknown> }).microApp
      ? Object.keys((window as unknown as { microApp: Record<string, unknown> }).microApp)
      : [],
    isInIframe: window.parent !== window,
    location: window.location.href,
  })

  // 简化的路由处理函数
  const handleRouteChange = (targetRoute: string, source: string) => {
    console.log(`[${source}] 要求跳转到:`, targetRoute)
    console.log('当前路由:', router.currentRoute.value.path)

    if (router.currentRoute.value.path !== targetRoute) {
      console.log(`路由跳转: ${router.currentRoute.value.path} -> ${targetRoute}`)
      router
        .push(targetRoute)
        .then(() => {
          console.log(`[${source}] 路由跳转成功:`, router.currentRoute.value.path)
          console.log('当前组件:', router.currentRoute.value.name)
        })
        .catch((err) => {
          console.warn(`[${source}] 路由跳转失败:`, err)
        })
    } else {
      console.log(`[${source}] 已在目标路由:`, targetRoute)
    }
  }

  // 获取初始路由的函数
  const getInitialRoute = (): string => {
    try {
      // @ts-expect-error 微前端全局对象可能不存在
      const microAppData = window.microApp?.getData()
      if (microAppData && microAppData.childRoute) {
        console.log('从初始数据获取路由:', microAppData.childRoute)
        return microAppData.childRoute
      }
    } catch (e) {
      console.log('无法获取初始数据:', e)
    }
    return '/' // 默认返回首页
  }

  // 标记是否已经设置过初始路由
  let initialRouteSet = false
  let targetInitialRoute = '/'

  // 在路由器准备就绪前设置初始路由
  const initialRoute = getInitialRoute()
  if (initialRoute !== '/') {
    console.log('设置初始路由为:', initialRoute)
    targetInitialRoute = initialRoute
    initialRouteSet = true
    // 直接替换当前路由，避免闪烁
    router
      .replace(initialRoute)
      .then(() => {
        console.log('初始路由设置完成:', router.currentRoute.value.path)
      })
      .catch((err) => {
        console.warn('设置初始路由失败:', err)
        initialRouteSet = false
      })
  }

  // 添加路由守卫，防止意外的路由跳转
  router.beforeEach((to, from, next) => {
    console.log('>>> 路由守卫检查:', `从 ${from.path} 到 ${to.path}`)

    // 如果正在设置初始路由，并且目标路由不是预期的，则阵止
    if (
      initialRouteSet &&
      to.path === '/' &&
      targetInitialRoute !== '/' &&
      from.path !== targetInitialRoute
    ) {
      console.log('阻止意外的首页跳转，重定向到:', targetInitialRoute)
      next(targetInitialRoute)
      return
    }

    next()
  })

  // 等待路由器准备就绪后处理后续数据变化
  router.isReady().then(() => {
    console.log('路由器已准备就绪')
    console.log('当前路由状态:', router.currentRoute.value.path, router.currentRoute.value.name)

    // 延迟重置标记，允许后续的正常路由跳转
    setTimeout(() => {
      if (initialRouteSet) {
        console.log('重置初始路由设置标记，允许后续路由跳转')
        initialRouteSet = false
      }
    }, 1000) // 给足够时间让初始化完成
  })

  // 在全局作用域中添加数据监听（不依赖路由器准备）
  // 尝试多种事件监听方式
  const setupDataListener = () => {
    console.log('设置数据监听器')

    // 方式1：监听window的datachange事件
    window.addEventListener('datachange', (e: Event) => {
      const customEvent = e as CustomEvent
      console.log('[Window] 接收到主应用数据变化:', customEvent.detail)
      if (customEvent.detail && customEvent.detail.childRoute) {
        const targetRoute = customEvent.detail.childRoute
        const dataKey = customEvent.detail.dataKey
        console.log('[Window] 数据更新key:', dataKey, '目标路由:', targetRoute)

        setTimeout(() => {
          handleRouteChange(targetRoute, 'Window数据监听')
        }, 50)
      }
    })

    // 方式2：监听micro-app全局对象
    // @ts-expect-error 微前端全局对象可能不存在
    if (window.microApp && typeof window.microApp.addDataListener === 'function') {
      console.log('使用microApp.addDataListener监听数据变化')
      // @ts-expect-error 微前端全局对象可能不存在
      window.microApp.addDataListener((data: { childRoute?: string; dataKey?: number }) => {
        console.log('[MicroApp] 接收到主应用数据变化:', data)
        if (data && data.childRoute) {
          const targetRoute = data.childRoute
          const dataKey = data.dataKey
          console.log('[MicroApp] 数据更新key:', dataKey, '目标路由:', targetRoute)

          setTimeout(() => {
            handleRouteChange(targetRoute, 'MicroApp数据监听')
          }, 50)
        }
      })
    }

    // 方式3：轮询检查数据变化（fallback方案）
    let lastDataKey = 0
    const pollDataChange = () => {
      try {
        // @ts-expect-error 微前端全局对象可能不存在
        const currentData = window.microApp?.getData()
        if (currentData && currentData.dataKey && currentData.dataKey !== lastDataKey) {
          console.log('[轮询] 检测到数据变化:', currentData)
          lastDataKey = currentData.dataKey

          if (currentData.childRoute) {
            setTimeout(() => {
              handleRouteChange(currentData.childRoute, '轮询数据监听')
            }, 50)
          }
        }
      } catch {
        // 忽略轮询错误
      }
    }

    // 每100ms检查一次数据变化
    setInterval(pollDataChange, 100)
  }

  // 立即设置监听器
  setupDataListener()

  // 添加路由守卫，进行调试
  router.afterEach((to, from) => {
    console.log('>>> 路由跳转完成')
    console.log('从:', from.path, from.name)
    console.log('到:', to.path, to.name)
  })

  // 清理函数，避免 URL 错误
  window.addEventListener('beforeunload', () => {
    console.log('子应用 A 准备卸载')
  })
}

export default router
